package com.jgdt.demo.api;

import java.util.WeakHashMap;
import com.jgdt.demo.AppContext;
import com.librariy.json.JsonObject;
import com.librariy.net.HttpClient;
import com.librariy.util.UIHelper;
public class SysInterface {
    private static WeakHashMap<String, JsonObject> dataCache = new WeakHashMap<>();
    public static void reset() {
        dataCache.clear();
    }
    private static JsonObject opt(String key,JsonObject fallback) {
        JsonObject retObj=dataCache.get(key);
        return (retObj==null?fallback:retObj);
    }
    private static void set(String key,JsonObject value) {
        dataCache.remove(key);
        dataCache.put(key, value);
    }
    private static void remove(String key) {
        dataCache.remove(key);
    }
    public static class User{
        private static String KEY=User.class.getName();
        public static void reset() {
            SysInterface.remove(KEY);
        }
        public static void get(boolean useCache,final Callback mCallback) {
            if(!useCache) User.reset();
            JsonObject retValue=SysInterface.opt(KEY, null);
            if (retValue!=null&&(System.currentTimeMillis()-retValue.BaselineTime)<120000) {
                if (mCallback != null)
                    mCallback.onLoaded(retValue);
                return;
            }
            dataCache.remove(KEY);
            JsonRequest request = new JsonRequest(JsonRequest.Method.GET, "/base/user/getUser");
            HttpClient.request(request, new JsonResponse() {
                public void onCompleted(boolean success, int code, String message, JsonObject originObject) {
                    UIHelper.dismissDialog();
                    if(!success){
                        UIHelper.showToast(AppContext.I, "无法获取用户信息");
                        return;
                    }
                    JsonObject data = originObject.optJsonObject(ResponseKey.data,new JsonObject());
                    SysInterface.set(KEY, data);
                    if (mCallback == null) return;
                    mCallback.onLoaded(SysInterface.opt(KEY, new JsonObject()));
                }
            });
            //请求结束
        }
    }
    public interface Callback {
        void onLoaded(JsonObject result);
    }
}